package behaviours.curator;

import agents.CuratorAgent;
import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.SimpleBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public class ListenForTourItemQuestions extends CyclicBehaviour {

    private CuratorAgent curatorAgent;
    private final AID inventor;

    public ListenForTourItemQuestions(CuratorAgent agent, AID inventorAID){
            super(agent);
            this.curatorAgent = agent;
            this.inventor = inventorAID;
    }

    @Override
    public void action() {
        ACLMessage msg = curatorAgent.receive(MessageTemplate.MatchPerformative(ACLMessage.REQUEST));
        if (msg != null){
            curatorAgent.addBehaviour(new QueryInventorAgentForInfoAndSendItToSenderBehaviour(msg));
        } else {
                block();
        }
    }

    private class QueryInventorAgentForInfoAndSendItToSenderBehaviour extends SimpleBehaviour{
        private ACLMessage msgReceived;
        private AID sender;
        private boolean sent;
        private boolean done;
        
        public QueryInventorAgentForInfoAndSendItToSenderBehaviour(ACLMessage msg){
            this.msgReceived = msg;
            this.sender = msg.getSender();
            sent = false;
            done = false;
        }
        
        @Override
        public void action() {
            if (sent){
                ACLMessage msg = curatorAgent.receive(MessageTemplate.MatchSender(inventor));
                if (msg != null){
                    System.out.println("Curator: Reveived answer from inventor, sending to profiler");
                    msg.clearAllReceiver();
                    msg.addReceiver(sender);
                    msg.setSender(curatorAgent.getAID());
                    curatorAgent.send(msg);
                    done = true;
                } else {
                    block();
                }
                
            } else {
                System.out.println("Curator: Received request from profiler, sending to inventor");
                msgReceived.clearAllReceiver();
                msgReceived.addReceiver(inventor);
                msgReceived.setSender(curatorAgent.getAID());

                curatorAgent.send(msgReceived);

                sent = true;
            }
        }

        @Override
        public boolean done() {
            return done;
        }

    }

}
